<template>
  <div class="approve-index">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>审批新申请</h3>
        </div>
      </template>

      <div class="body-card">
        <div v-for="(item, index) in moduleList" :key="index" class="module-section">
          <div v-if="item.list && item.list.length > 0" class="section-content">
            <div class="card-header">
              <strong>{{ item.title }}</strong>
            </div>
            <div class="square">
              <el-row :gutter="10">
                <el-col
                  v-for="(subItem, subIndex) in item.list"
                  :key="subIndex"
                  :span="4"
                  class="square-item"
                  @click="handleApply(subItem)"
                >
                  <div class="square-content">
                    <i :class="`iconfont ${subItem.icon}`"></i>
                    <span>{{ subItem.title }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>

        <div class="admin-tip">
          如果是【日常办公数据管理员】，可查看全体员工的审批申请记录，去查
          <el-link type="primary" @click="goToAllApprovals">『全部审批』</el-link>
        </div>
      </div>
    </el-card>

    <el-card class="approval-list-card">
      <template #header>
        <div class="card-header">
          <h3>审批列表</h3>
        </div>
      </template>

      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="全部" name="0"></el-tab-pane>
        <el-tab-pane label="待审批" name="1"></el-tab-pane>
        <el-tab-pane label="审批通过" name="2"></el-tab-pane>
        <el-tab-pane label="审批拒绝" name="3"></el-tab-pane>
      </el-tabs>

      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keywords" placeholder="请输入关键词" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="searchApprovals">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="loading"
        :data="approvalList"
        border
        :height="tableHeight"
        style="width: 100%"
      >
        <el-table-column prop="types_name" label="审批类型" width="100" align="center" />
        <el-table-column prop="check_status" label="审核状态" width="110" align="center">
          <template #default="{ row }">
            <span :class="`check-status-color-${row.check_status}`">
              『{{ row.check_status_str }}』
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="admin_name" label="申请人" width="90" align="center" />
        <el-table-column prop="create_time" label="申请时间" width="150" align="center" />
        <el-table-column prop="department" label="所属部门" width="120" align="center" />
        <el-table-column prop="check_users" label="当前审批人" />
        <el-table-column prop="check_copy_users" label="抄送人员" width="150" />
        <el-table-column label="操作" width="60" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import axios from '../../utils/request'
  import { Search } from '@element-plus/icons-vue'
  import { useRouter } from 'vue-router'

  // 定义审批列表项的类型
  interface ApprovalItem {
    id: number | string
    types_name: string
    check_status: number
    check_status_str: string
    admin_name: string
    create_time: string
    department: string
    check_users: string
    check_copy_users: string
    view_url: string
    [key: string]: any // 允许其他属性
  }

  // 数据相关
  const approvalList = ref<ApprovalItem[]>([])
  const loading = ref(false)
  const activeTab = ref('0')
  const currentPage = ref(1)
  const pageSize = ref(20)
  const total = ref(0)
  const tableHeight = ref('full-152')

  // 搜索表单
  const searchForm = reactive({
    keywords: '',
    status: '0',
  })

  const router = useRouter()

  // 审批模块列表
  const moduleList = ref([
    {
      title: '财务管理',
      list: [
        { title: '费用报销', icon: 'icon-reimbursement', url: '/reimbursement/apply' },
        { title: '借款申请', icon: 'icon-loan', url: '/loan/apply' },
        { title: '付款申请', icon: 'icon-payment', url: '/payment/apply' },
      ],
    },
  ])

  // 处理申请点击
  const handleApply = (item: { title: string; icon: string; url: string }) => {
    router.push(item.url)
  }

  // 跳转到全部审批
  const goToAllApprovals = () => {
    router.push('/approve/all')
  }

  // 获取全部审批列表
  const getAllApprovalList = async () => {
    try {
      loading.value = true
      const response = await axios.get('/home/approve/index', {
        params: {
          status: activeTab.value,
          keywords: searchForm.keywords,
          page: currentPage.value,
          limit: pageSize.value,
        },
      })

      if (response.data?.code === 0) {
        // 确保赋值时类型正确
        approvalList.value = (response.data?.data?.list || []) as ApprovalItem[]
        total.value = response.data?.data?.total || 0
      } else {
        ElMessage.error(response.data?.msg || '获取审批列表失败')
      }
    } catch (error) {
      ElMessage.error('获取审批列表失败')
    } finally {
      loading.value = false
    }
  }

  // 查看详情
  const viewDetail = (row: any) => {
    router.push(row.view_url + '?id=' + row.id)
  }

  // 处理标签页切换
  const handleTabChange = (name: string) => {
    searchForm.status = name
    activeTab.value = name
    currentPage.value = 1
    getAllApprovalList()
  }

  // 处理分页大小变化
  const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    getAllApprovalList()
  }

  // 处理当前页变化
  const handleCurrentChange = (val: number) => {
    currentPage.value = val
    getAllApprovalList()
  }

  // 搜索审批
  const searchApprovals = () => {
    currentPage.value = 1
    getAllApprovalList()
  }

  // 重置搜索
  const resetSearch = () => {
    searchForm.keywords = ''
    currentPage.value = 1
    getAllApprovalList()
  }

  // 初始化
  onMounted(() => {
    getAllApprovalList()
  })
</script>

<style scoped>
  .approve-index {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .body-card {
    background-color: #fff;
    border: 1px solid #eee;
  }

  .module-section {
    margin-bottom: 20px;
  }

  .card-header strong {
    font-size: 16px;
    font-weight: bold;
  }

  .square {
    padding: 10px 0;
  }

  .square-item {
    border: 1px solid #f5f5f5;
    border-left: 0;
    cursor: pointer;
  }

  .square-item:nth-child(6n) {
    border-right: 0;
  }

  .square-content {
    padding: 12px 0;
    height: 50px;
    text-align: center;
    background-color: #fff;
    color: #666;
  }

  .square-content:hover {
    color: #4285f4;
    background-color: #fafafa;
  }

  .square-content i {
    font-size: 28px;
    font-weight: 800;
    display: block;
    padding-bottom: 3px;
    color: #4285f4;
  }

  .admin-tip {
    padding: 16px 0;
    text-align: center;
    color: #ffb800;
  }

  .approval-list-card {
    margin-top: 20px;
  }

  .check-status-color-0::before,
  .check-status-color-4::before {
    content: '待审批';
    color: #409eff;
  }

  .check-status-color-1::before {
    content: '审批通过';
    color: #67c23a;
  }

  .check-status-color-2::before {
    content: '审批拒绝';
    color: #f56c6c;
  }

  .check-status-color-3::before {
    content: '已撤回';
    color: #909399;
  }
</style>
